package org.penguin.study.bk.websocket;

import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.util.WebsocketUtil;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocketServerEndpoint {

    public static Map<Session, String> socketMap = new ConcurrentHashMap<>();

    // 连接建立成功触发的方法
    @OnOpen
    public void onOpen(@PathParam("name") String name, Session session) {
        socketMap.put(session, name);
        InetSocketAddress inetSocketAddress = WebsocketUtil.getRemoteAddress(session);
        log.info("webSocket成功与客户端({})建立连接: {}", inetSocketAddress == null ? "未知" : inetSocketAddress.getAddress().getHostAddress(), name);
    }

    // 连接关闭时触发的方法
    @OnClose
    public void onClose(Session session) {
        log.info("webSocket与客户端断开连接: {}");
        socketMap.remove(session);
    }

    // 收到客户端消息后触发的方法
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.printf("收到来自%s的消息:%s%n", session, message);
        try {
            String name = socketMap.get(session);
            for (Session client : socketMap.keySet()) {
                client.getBasicRemote().sendText(name + "说：" + message);
            }
        } catch (IOException e) {
            log.error("webSocket处理消息时出错: {}", e.getMessage());
        }
    }

    // 发生错误时触发的方法
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("webSocket发生错误: {}", error.getMessage());
        socketMap.remove(session);
    }
}
